// 放置商品模块的所有接口
const express = require('express')

// 调用express中GoodsRouter方法创建路由对象
const goodsRouter = express.Router()

// 接下来就需要编写接口
// GoodsRouter.get(url地址, callback)
// GoodsRouter.post(url地址, callback)
// 数据库对象引入
let con = require('../db/db')

goodsRouter.get('/list', (req, res) => {
  // order by 字段名称  根据什么字段查询  desc表示降序  asc升序
  let sql = `select * from goods order by id desc`
  con.query(sql, (err, results, fields) => {
    if (err) throw err
    // console.log(results)
    if (results.length !== 0) {
      res.json({
        code: 200,
        message: '查询数据成功',
        data: results
      })
    } else if (results.length === 0) {
      res.json({
        code: 1003,
        message: '当前数据为空',
        data: []
      })
    }

  })
})

// 查询指定id值的数据
goodsRouter.post('/list/:id', (req, res) => {
  let { id } = req.params
  let sql = `select * from goods where id = ${id}`
  con.query(sql, (err, results, fields) => {
    if (err) throw err
    console.log(results)
    if (results.length !== 0) {
      res.json({
        code: 200,
        message: 'ok',
        data: results
      })
    }
  })
})

// 添加数据的接口
goodsRouter.post('/add', (req, res) => {
  console.log(req.body)
  // 接受参数
  let { good_name, good_price, good_count } = req.body
  let sql = `insert into goods(good_name,good_price,good_count) value("${good_name}",${good_price},${good_count})`
  con.query(sql, (err, results) => {
    // 判断受影响行数决定添加成功与否
    if (!results.affectedRows) {
      res.json({
        code: 1000,
        message: '插入数据失败'
      })
    } else {
      res.json({
        code: 200,
        message: '插入数据成功',
      })
    }
  })
})

// 更新数据的接口  修改id为1商品价格为1999  
goodsRouter.post('/update/:id', (req, res) => {
  let { id } = req.params
  let { price, count } = req.body

  console.log(price)

  let sql = `update goods set good_price=${price},good_count=${count} where id = ${id}`
  con.query(sql, (err, results) => {
    console.log(results)
    if (!results.affectedRows) {
      res.json({
        code: 1001,
        message: '更新失败'
      })
    } else {
      res.json({
        code: 1002,
        message: '更新成功',
      })
    }
  })

})

// 删除数据的接口
goodsRouter.post('/delete/:id', (req, res) => {
  let { id } = req.params
  let sql = `delete from goods where id = ${id}`
  con.query(sql, (err, results) => {
    if (!results.affectedRows) {
      res.json({
        code: 1001,
        message: '删除失败'
      })
    } else {
      res.json({
        code: 1002,
        message: '删除成功',
      })
    }
  })

})

// 将商品模块的路由暴露
module.exports = goodsRouter